package com.leetroll.media.job;

import com.leetroll.api.service.MetricService;
import com.leetroll.common.entity.Metric;
import com.leetroll.common.utils.AliyunOSSUtil;
import com.leetroll.common.utils.BaiduTranslateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * poliigon网站的资源入库 （此服务后面放到别的模块）
 */
@Service
@Slf4j
public class Job_Metric {

    private final MetricService metricService;

    @Autowired
    public Job_Metric(MetricService metricService) {
        this.metricService = metricService;
    }

    /**
     * 根据文件夹目录生成metric
     */
    public void generateMetrics() throws IOException {
//        File folder = new File("F:\\_dev\\leetroll\\配置资源\\分类metric\\贴图");
        File folder = new File("F:\\_dev\\leetroll\\配置资源\\分类metric\\模型");

        if (!folder.exists() || !folder.isDirectory()) return;
        File[] files = folder.listFiles();
        List<Metric> metrics = new ArrayList<>();
        if (files == null) return;
        for (File file : files) {
            String name = file.getName().split("\\.")[0];
            String zhName = BaiduTranslateUtil.translate(name);
            Metric metric = new Metric();
            metric.setParentId(1L);
            metric.setName(zhName);
            metric.setAlias(name);
            metric.setCreateTime(new Date());
            metric.setUpdateTime(new Date());

            String path = "cat/7/metrics/" + file.getName();
            AliyunOSSUtil.upload(path, Files.newInputStream(file.toPath()));
            String url = AliyunOSSUtil.GetUrl(path, 30);//10年有效期

            metric.setPreview(url);
            metrics.add(metric);

        }
        metricService.saveBatch(metrics);
        log.info("metric 插入任务完成");
    }

    public static void main(String[] args) {
        String url = AliyunOSSUtil.GetUrl("cat/1/metrics/hdri.jpg", 10);//10年有效期
        System.out.println(url);
    }

}
